{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ebb58893",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''\n",
    "os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b3345002",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2023-11-02 06:05:42,310] [INFO] [real_accelerator.py:133:get_accelerator] Setting ds_accelerator to cuda (auto detect)\n"
     ]
    }
   ],
   "source": [
    "from transformers import MistralConfig, MistralForCausalLM, AutoTokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f54d2eea",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "checkpoint-7400  checkpoint-7500\r\n"
     ]
    }
   ],
   "source": [
    "!ls fpf-7b-32k"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "931be6c4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "MistralConfig {\n",
       "  \"_name_or_path\": \"mesolitica/mistral-7b-4096-fpf\",\n",
       "  \"architectures\": [\n",
       "    \"MistralForCausalLM\"\n",
       "  ],\n",
       "  \"bos_token_id\": 1,\n",
       "  \"eos_token_id\": 2,\n",
       "  \"hidden_act\": \"silu\",\n",
       "  \"hidden_size\": 4096,\n",
       "  \"initializer_range\": 0.02,\n",
       "  \"intermediate_size\": 14336,\n",
       "  \"max_position_embeddings\": 32768,\n",
       "  \"model_type\": \"mistral\",\n",
       "  \"num_attention_heads\": 32,\n",
       "  \"num_hidden_layers\": 4,\n",
       "  \"num_key_value_heads\": 8,\n",
       "  \"rms_norm_eps\": 1e-05,\n",
       "  \"rope_theta\": 10000.0,\n",
       "  \"sliding_window\": 4096,\n",
       "  \"tie_word_embeddings\": false,\n",
       "  \"torch_dtype\": \"bfloat16\",\n",
       "  \"transformers_version\": \"4.34.0\",\n",
       "  \"use_cache\": true,\n",
       "  \"vocab_size\": 32000\n",
       "}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "half_config = MistralConfig.from_pretrained('fpf-7b-32k/checkpoint-7500', \n",
    "                                             num_hidden_layers = 4)\n",
    "half_config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b994bc75",
   "metadata": {},
   "outputs": [],
   "source": [
    "small = MistralForCausalLM(half_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6ef3bbcb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1134596096"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum(p.numel() for p in small.parameters())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "48f037b1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9bb8d1a42e244e22a7a8208e082d0884",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading checkpoint shards:   0%|          | 0/2 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "model = MistralForCausalLM.from_pretrained('fpf-7b-32k/checkpoint-7500')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b75c4d5f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.nn as nn\n",
    "\n",
    "def copy_layers(src_layers, dest_layers, layers_to_copy):\n",
    "    layers_to_copy = nn.ModuleList([src_layers[i] for i in layers_to_copy])\n",
    "    assert len(dest_layers) == len(layers_to_copy), f\"{len(dest_layers)} != {len(layers_to_copy)}\"\n",
    "    dest_layers.load_state_dict(layers_to_copy.state_dict())\n",
    "\n",
    "layers_to_copy = [0,1,2,3]\n",
    "\n",
    "copy_layers(model.model.layers, small.model.layers, layers_to_copy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "49004cbc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.model.embed_tokens.load_state_dict(model.model.embed_tokens.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "5ce896c6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.model.norm.load_state_dict(model.model.norm.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "1d519f55",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.lm_head.load_state_dict(model.lm_head.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "d7688a90",
   "metadata": {},
   "outputs": [],
   "source": [
    "small.save_pretrained(\"1b\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "642e20ce",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
      "Using pad_token, but it is not set yet.\n",
      "Using pad_token, but it is not set yet.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "('1b/tokenizer_config.json',\n",
       " '1b/special_tokens_map.json',\n",
       " '1b/tokenizer.model',\n",
       " '1b/added_tokens.json',\n",
       " '1b/tokenizer.json')"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained('fpf-7b-32k/checkpoint-7500')\n",
    "tokenizer.save_pretrained(\"1b\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "df0b968e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "total 4.3G\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu   42 Nov  2 06:11 added_tokens.json\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu  617 Nov  2 06:11 config.json\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu  111 Nov  2 06:11 generation_config.json\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu 4.3G Nov  2 06:11 pytorch_model.bin\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu  145 Nov  2 06:11 special_tokens_map.json\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu 1.8M Nov  2 06:11 tokenizer.json\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu 482K Nov  2 06:11 tokenizer.model\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu  953 Nov  2 06:11 tokenizer_config.json\r\n"
     ]
    }
   ],
   "source": [
    "!ls -lh 1b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "329000ab",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
